<template>
  <div class="mobile-preview">
    <div class="mobile-preview-top"></div>
    <div class="tool-box">
      <div class="tool-item music" @click="musicManage"><i class="el-icon-mic"></i>音乐</div>
    </div>
    <div class="music-box" v-if="this.selectedRowId">
      <div class="music-item">
        <audio
          ref="audio"
          class="aud"
          autoplay
          loop>
        <source :src="this.selectedMusicUrl" />
        </audio>

      </div>
    </div>
    <div class="mobile-preview-body">
      <activity-tpl1 v-model="modelValue" />
    </div>
    <el-dialog title="选择音乐" :visible.sync="musicOpen" width="550px" append-to-body>
      <div>
        <el-radio-group v-model="queryParams.type" size="mini" @input="getMusicList">
          <teleport v-for="dict in dict.type.music_type" :key="dict.value">
            <el-radio-button :label="dict.value" :value="dict.value">{{ dict.label }}</el-radio-button>
          </teleport>
        </el-radio-group>
      </div>
      <el-table
        :show-header=false
        :data="musicDataList"
        ref="radioTable"
        :header-cell-style="{background:'#eef1f6',color:'#909399'}"
        fixed
        @row-click="rowClick"
        @selection-change="selectionChange"
        stripe
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="name">
          <template slot-scope="scope">
            <div class="audio-base">
              <div class="audio-name">
                <span>{{ scope.row.name }}</span>
              </div>
              <div class="audio-url">
                <audio controls ref="audio" class="aud">
                  <source :src="scope.row.url" />
                </audio>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getMusicList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleAdd" icon="el-icon-upload2">上传音乐</el-button>
        <el-button size="mini" type="primary" @click="selected">确 定</el-button>
        <el-button size="mini" @click="musicOpen = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".mp3" :auto-upload="false" drag
                 :headers="upload.headers" :action="upload.url" :data="upload.data" :disabled="upload.isUploading"
                 :on-change="handleFileChange"
                 :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或 <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入mp3 格式文件！</div>
      </el-upload>
      <div class="music-type">
        <span>音乐类型：</span>
        <el-select style="width: 50%" size="mini" v-model="upload.type" placeholder="音乐类型">
          <el-option
            v-for="dict in dict.type.music_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </div>
      <div class="is-public">
        <span class="is-public-title">是否给其他商家使用：</span>
        <el-switch v-model="upload.is_public"></el-switch>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitFileForm">确 定</el-button>
        <el-button size="mini" @click="uploadMusicCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import activityTpl1 from "./components/mobilePreview/template/activityTpl1"
import { musicList,addMusic } from "@/api/triones/activityTool";
import {getToken} from "@/utils/auth";
export default {
  name: "mobilePreview",
  dicts: ['music_type'],
  components: {
    activityTpl1,
  },
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      musicOpen: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: undefined
      },
      musicDataList: [],
      total: 0,
      selectData :{},
      selectedRowId: null,
      selectedMusicUrl: null,
      upload: {
        is_public: false,
        type: 'hot',
        open: false,
        title: '',
        isUploading: false,
        url: process.env.VUE_APP_BASE_API + '/infra/file/upload',
        headers: { Authorization: 'Bearer ' + getToken() },
        data: {}
      }
    }
  },
  computed: {
    modelValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
  },
  watch: {
    value: {
      handler(val) {
        if (val.base_style_config.music.id) {
          this.selectedRowId = val.base_style_config.music.id;
          this.selectedMusicUrl = val.base_style_config.music.url;
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    /** 音频管理 */
    musicManage() {
      this.getMusicList();
      this.musicOpen = true;
    },
    /** 选中音乐 */
    selected() {
      if (this.selectData) {
        this.value.base_style_config.music.id = this.selectData.id;
        this.selectedRowId = this.selectData.id;
        this.value.base_style_config.music.url = this.selectData.url;
        this.selectedMusicUrl = this.selectData.url;
      } else {
        this.value.base_style_config.music.id = '';
        this.value.base_style_config.music.url = '';
        this.selectedRowId = '';
        this.selectedMusicUrl = '';
      }
      this.musicOpen = false;
    },
    /** 上传提交 */
    submitFileForm() {
      this.$refs.upload.submit();
    },
    uploadMusicCancel() {
      this.upload.type = 'hot';
      this.upload.is_public = false;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
    },
    /** 获取音乐列表 */
    getMusicList() {
      musicList(this.queryParams).then(response => {
        this.musicDataList = response.rows;
        this.total = response.total;
        if (this.selectedRowId) {
          this.musicDataList.forEach(item => {
            if (this.selectedRowId == item.id) {
              this.$nextTick(() => {
                this.$refs.radioTable.toggleRowSelection(item)
              })
            }
          })
        }
      })
    },
    rowClick(row, column) {
      this.$refs.radioTable.toggleRowSelection(row);
    },
    selectionChange(val) {
      if(val.length>1){
        this.$refs.radioTable.clearSelection()
        this.$refs.radioTable.toggleRowSelection(val.pop())
      }else{
        this.selectData = val.pop()
      }
    },
    handleAdd() {
      this.upload.open = true
      this.upload.title = '上传文件'
    },
    /** 处理上传的文件发生变化 */
    handleFileChange(file, fileList) {
    },
    /** 处理文件上传中 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true // 禁止修改
    },
    handleFileSuccess(response, file, fileList) {
      if (response.code == 200) {
        const fileFrom = {
          url: response.data.url,
          name: response.data.name,
          type: this.upload.type ? this.upload.type : 'hot',
          isPublic: this.upload.is_public ? 1 : 0
        }
        addMusic(fileFrom).then(response => {
          this.upload.type = 'hot';
          this.upload.is_public = false;
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          // 提示成功，并刷新
          this.$modal.msgSuccess('上传成功');
          this.queryParams.pageNum = 1;
          this.getMusicList()
        })
      } else {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
      }
    }
  }
}
</script>

<style lang="scss" scoped>

::v-deep .el-radio-button {
  margin: 5px;
}

::v-deep .el-radio-button__inner {
  border-left: 1px solid #dcdfe6;
  border-radius: 10px;
}

::v-deep .el-dialog__body{
  padding: 10px;
}

.mobile-preview {
  position: relative;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  overflow-x: hidden;
  min-height: 812px;
  overflow-y: scroll;
  margin-top: 30px;
  margin-bottom: 30px;
  .mobile-preview-top {
    width: 375px;
    height: 24px;
    background: url("~@/assets/images/activity/icon-mobile-top.jpg");
  }

  .mobile-preview-body {
    width: 375px;
    height: 812px - 24px;
    overflow-y: scroll;
  }
}

.tool-box {
  position: absolute;
  top: 90px;
  left: calc(50% + 180px);
  transform: translateX(-100%);
  display: flex;
  z-index: 210;
  .tool-item {
    display: flex;
    align-items: center;
    line-height: 32px;
    font-size: 14px;
    color: #2254f5;
    background: #e5ecff;
    border-radius: 8px;
    border: 2px solid #2254f5;
    box-shadow: 0 0 6px #7ac0ff;
    padding: 0 12px;
    cursor: pointer;
  }
  .music {
    margin-right: 12px;
    width: 70px;
    height: 35px;
  }
}

.music-box {
  position: absolute;
  top: 90px;
  left: 10px;
  display: flex;
  z-index: 210;
  width: 30px;
  height: 30px;
  .music-item {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, .55);
    background-size: 100% 100%;
    background-image: url("~@/assets/images/activity/music-off.png");
    animation: rotating-462e8206 1.2s linear infinite;
    transform-origin: center center;
    -webkit-transform: rotate(360deg);
    -moz-animation: rotation 1.5s linear infinite;
    -webkit-animation: rotation 1.5s linear infinite;
    -o-animation: rotation 1.5s linear infinite;
  }
  @-webkit-keyframes rotation {
    from {
      -webkit-transform: rotate(0deg);
    }
    to {
      -webkit-transform: rotate(360deg);
    }
  }
}

.audio-base {
  display: flex;
  justify-content: space-between;
  .audio-name {
    align-content: center;
  }
  .audio-url {
    align-content: center;
    text-align: right;
    .aud {
      height: 30px;
      align-content: center;
    }
  }
}

.music-type {
  padding: 10px 0;
}

.is-public {
  width: 100%;
  align-content: center;
  .is-public-title {
    font-size: 14px;
    vertical-align: middle;
  }
}
</style>
